<template>
  <!-- 搜索栏 -->
  <el-card class="search-card">
    <el-form :model="searchForm" label-width="80px" inline>
      <el-form-item label="工单编码">
        <el-input v-model="searchForm.productionOrderCode" placeholder="请输入工单编码" clearable/>
      </el-form-item>
      <el-form-item label="工单名称">
        <el-input v-model="searchForm.productionOrderName" placeholder="请输入工单名称" clearable/>
      </el-form-item>
      <el-form-item label="来源单据">
        <el-select style="width: 120px" clearable v-model="searchForm.productionOrderSource"
                   placeholder="请选择来源单据">
          <el-option label="客户订单" :value="1"/>
          <el-option label="库存备货" :value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item label="产品编号">
        <el-input v-model="searchForm.materialCode" placeholder="请输入产品编号" clearable/>
      </el-form-item>
      <el-form-item label="产品名称">
        <el-input v-model="searchForm.materialName" placeholder="请输入产品名称" clearable/>
      </el-form-item>
      <el-form-item label="客户编号">
        <el-input v-model="searchForm.customerCode" placeholder="请输入客户编号" clearable/>
      </el-form-item>
      <el-form-item label="客户名称">
        <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable/>
      </el-form-item>
      <!--日期选择器-->
      <el-form-item label="需求时间">
        <el-date-picker
            v-model="searchForm.requestDate"
            type="datetime"
            placeholder="请选择需求时间"
            format="YYYY-MM-DD HH:mm:ss"
            date-format="MMM DD, YYYY"
            time-format="HH:mm"
            style="width: 200px;"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
        <el-button @click="resetSearch" :icon="Refresh">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 列表 -->
  <el-card class="table-card">
    <el-table :data="productionOrderList" border stripe @selection-change="handleSelectionChange">
      <el-table-column prop="productionOrderCode" label="工单编码" min-width="120px" fixed>
        <template #default="scope">
          <el-link type="primary" @click="handleGetById(scope.row)">{{ scope.row.productionOrderCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="productionOrderName" label="工单名称" fixed/>
      <el-table-column prop="productionOrderSource" label="来源类型">
        <template #default="scope">
          {{ scope.row.productionOrderSource == 1 ? '客户订单' : '库存备货' }}
        </template>
      </el-table-column>
      <el-table-column prop="productionOrderCode" label="订单编号"/>
      <el-table-column prop="materialCode" label="产品编号"/>
      <el-table-column prop="materialName" label="产品名称"/>
      <el-table-column prop="material.specification" label="规格" fixed/>
      <el-table-column prop="material.unit.name" label="单位" fixed/>
      <el-table-column prop="productionOrderQuantity" label="工单数量" fixed/>
      <el-table-column prop="productionOrderQuantity" label="调整数量" fixed/>
      <el-table-column label="已生产数量" fixed>
        <template #default>0</template>
      </el-table-column>
      <el-table-column prop="customer.code" label="客户编号"/>
      <el-table-column prop="customer.name" label="客户名称"/>
      <el-table-column prop="requestDate" label="需求日期"/>
      <el-table-column prop="" label="排产状态"/>
      <el-table-column label="操作" fixed="right">
        <template #default="scope">
          <template v-if="scope.row.statusDictData?.dictValue == 4">
            <el-button type="info" text :icon="Edit" @click="handleEdit(scope.row)">排产</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 分页栏 -->
  <div class="pagination-container">
    <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>

  <!--弹窗-->
  <el-dialog
      v-model="proscheduleDialogVisabel" :title="dialogTitle" @close="dialogClose" width="60%">
    <el-form label-width="auto" :model="proscheduleForm" hide-required-asterisk :show-message="false">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工单编号">
            <el-link type="primary">{{ proscheduleForm.productionOrderCode }}</el-link>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工单名称">
            <el-input v-model="proscheduleForm.productionOrderName"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="来源类型" prop="productionOrderType">
            <el-radio-group v-model="proscheduleForm.productionOrderSource">
              <el-radio :label="1">客户订单</el-radio>
              <el-radio :label="2">库存备货</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单编号" prop="orderCode">
            <el-input v-model="proscheduleForm.orderCode"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="排产状态">
            <el-input v-model="proscheduleForm.status"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="产品编号" prop="materialCode">
            <el-input v-model="proscheduleForm.materialCode"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品名称" prop="materialName">
            <el-input v-model="proscheduleForm.materialName"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="规格型号" prop="materialSpecification">
            <el-input v-model="proscheduleForm.materialSpecification"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单位" prop="unit_id">
            <el-input v-model="proscheduleForm.unitId"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="工单数量" prop="productionOrderQuantity">
            <el-input v-model="proscheduleForm.productionOrderQuantity"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="需求日期" prop="requestDate">
            <el-date-picker
                v-model="proscheduleForm.requestDate"
                type="date"
                placeholder="请选择需求日期"
                value-format="yyyy-MM-dd"
                style="width: 100%;"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="客户编码" prop="customerCode">
            <el-input
                v-model="proscheduleForm.customerCode" clearable>
              <template #suffix>
                <el-icon style="cursor:pointer;" @click="showCustomerList">
                  <Search/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerName">
            <el-input v-model="proscheduleForm.customerName"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model="proscheduleForm.remark" placeholder="请输入内容"/>
      </el-form-item>
    </el-form>

    <el-tabs type="border-card" @tab-click="handleWorkflowTabClick">
      <el-tab-pane
          v-for="workflow in workflowList"
          :key="workflow.id"
          :name="workflow.id"
          :label="workflow.workflowName">
        <el-tabs @tab-click="handleProcessTabClick">
          <el-tab-pane
              v-for="process in workflow.processes"
              :key="process.id"
              :name="process.id"
              :label="process.processName">
            <el-row>
              <el-button-group>
                <el-button type="primary" @click="handleAddTask(process)">新增</el-button>
                <el-button type="warning" @click="handleEditTask(process)">修改</el-button>
                <el-button type="danger" @click="handleDeleteTask(process)">删除</el-button>
              </el-button-group>
            </el-row>
            <el-row>
              任务列表
              <el-table :data="process.taskList" border size="small">
                <el-table-column type="index" label="#" width="50"/>
                <el-table-column prop="taskName" label="任务名称" min-width="140"/>
                <el-table-column prop="workstationName" label="工作站" min-width="100"/>
                <el-table-column prop="scheduledQuantity" label="排产数量" width="80"/>
                <el-table-column prop="producedQuantity" label="已生产" width="80"/>
                <el-table-column prop="startProductionTime" label="开始时间" width="140">
                  <template #default="{row}">
                    {{ row.startProductionTime || '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="estimatedCompletionTime" label="预计完成" width="140">
                  <template #default="{row}">
                    {{ row.estimatedCompletionTime || '-' }}
                  </template>
                </el-table-column>
                <el-table-column prop="operation" label="状态" width="80"/>
                <el-table-column prop="productionDuration" label="时长(min)" width="90"/>
              </el-table>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="proscheduleDialogVisabel = false">关闭</el-button>
    </template>
  </el-dialog>
  <!-- 工序步骤弹窗 -->
  <el-dialog
      :title="workflowProcessDialogTitle"
      v-model="workflowProcessDialogVisible"
      width="80%"
      @close="handleDialogClose"
  >
    <el-row style="margin: 10px">
      <el-col :span="12">
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedTask.length === 0">批量删除</el-button>
      </el-col>
    </el-row>
    <el-col :span="24">
      <el-table
          :data="workflowProcessList"
          stripe
          border
          @selection-change="handleSelectionChange"
          style="width: 100%">
        <el-table-column type="selection" width="55"/>
        <el-table-column fixed="left" prop="id" label="ID"/>
        <el-table-column fixed="left" prop="stepOrder" label="序号"/>
        <el-table-column fixed="left" prop="process.processCode" label="工序编号"/>
        <el-table-column fixed="left" prop="process.processName" label="工序名称"/>
        <el-table-column fixed="left" prop="workstationCode" label="工作站编号"/>
        <el-table-column fixed="left" prop="workstationName" label="工作站名称"/>
        <el-table-column fixed="left" prop="proScheduleQuantity" label="排产数量"/>
        <el-table-column fixed="left" prop="proScheduleQuantity" label="已生产数量">
          {{ 0 }}
        </el-table-column>
        <el-table-column prop="nextProcess.processName" label="下一道工序">
          <template v-slot="scope">
            {{ scope.row.nextProcess ? scope.row.nextProcess.processName : '无' }}
          </template>
        </el-table-column>
        <el-table-column prop="relationNextDict.dictLabel" label="与下一道工序关系">
          <template v-slot="scope">
            {{ scope.row.nextProcess ? scope.row.relationNextDict.dictLabel : '无' }}
          </template>
        </el-table-column>
        <el-table-column prop="isCritical" label="关键工序">
          <template v-slot="scope">
            <el-tag :type="scope.row.isCritical == '1' ? 'success' : 'danger'">
              {{ scope.row.isCritical == '1' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="needInspection" label="质检确认">
          <template v-slot="scope">
            <el-tag :type="scope.row.needInspection == '1' ? 'success' : 'danger'">
              {{ scope.row.needInspection == '1' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="prepTime" label="准备时间(min)"/>
        <el-table-column prop="waitTime" label="等待时间(min)"/>
        <el-table-column prop="ganttColor" label="甘特图颜色">
          <template v-slot="scope">
            <el-color-picker v-model="scope.row.ganttColor" disabled/>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="small" @click="handlerAddWorkflowProcess(scope.row)">新增</el-button>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
    <template #footer>
      <el-button @click="exitProcessSteps">退出</el-button>
    </template>
  </el-dialog>

  <!--新增工作站弹窗-->
  <el-dialog
      title="选择工作站"
      v-model="productListDialogVisable"
      width="80%"
      @close="handleWorkstationDialogClose"
  >
    <el-row style="margin:15px">
      <!-- 修正：表单model绑定为searchWorkstationForm -->
      <el-form inline :model="searchWorkstationForm">
        <el-form-item label="工作站编号">
          <!-- 修正：v-model绑定为searchWorkstationForm.code -->
          <el-input v-model="searchWorkstationForm.code" placeholder="工作站编号"/>
        </el-form-item>
        <el-form-item label="工作站名称">
          <!-- 修正：v-model绑定为searchWorkstationForm.name -->
          <el-input v-model="searchWorkstationForm.name" placeholder="工作站名称"/>
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="loadWorkstationList">搜索</el-button>
          <el-button @click="resetSearchWorkstation">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row style="margin:15px">
      <el-radio-group v-model="selectedWorkstationCode" style="width: 100%">
        <el-table
            :data="workstationList"
            stripe
            border
            width="100%"
        >
          <el-table-column>
            <template #default="scope">
              <!-- 绑定工作站编码 -->
              <el-radio :value="scope.row.code"/>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="工作站编码"/>
          <el-table-column prop="name" label="工作站名称"/>
          <el-table-column prop="workshopId" label="所属车间编号"/>
          <el-table-column prop="location" label="工作站地点"/>
          <el-table-column prop="processId" label="所属工序编号"/>
          <el-table-column prop="description" label="工作站描述"/>
        </el-table>
      </el-radio-group>
    </el-row>
    <el-row>
      <el-button @click="doSelectWorkstation">确定</el-button>
    </el-row>
  </el-dialog>

</template>

<script setup>
/* ========== 依赖引入 ========== */
import {ref, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import {Search, Refresh, Edit} from '@element-plus/icons-vue'

/* ========== API 引入 ========== */
import {getProductionOrderList, getProductionOrderById} from '@/api/production-order.js'
import {getWorkflowByMaterialCode} from '@/api/workflow.js'
import {
  getWorkstationPage,
  getWorkstationByCode,
  addWorkstation,
  updateWorkstation,
  deleteWorkstation,
  batchDeleteWorkstation,
  changeWorkstationStatus,
  getWorkstationByWorkshopId
} from '@/api/workstation.js'
import {getProductionTaskByWorkflowId} from '@/api/productionTask.js'

/* ========== 基础数据 ========== */
const pagination = ref({currentPage: 1, pageSize: 10, total: 0})
const searchForm = ref({
  productionOrderCode: '',
  productionOrderName: '',
  productionOrderSource: '',
  materialCode: '',
  materialName: '',
  customerCode: '',
  customerName: '',
  requestDate: ''
})

/* ========== 弹窗 & 表单 ========== */
const proscheduleDialogVisabel = ref(false)
const dialogTitle = ref('')
const proscheduleForm = ref({})

/* ========== 工艺/任务 ========== */
const productionOrderList = ref([])
const workflowList = ref([])
const currentWorkflowId = ref()

/* ========== 工作站选择弹窗 ========== */
const productListDialogVisable = ref(false)
const selectedWorkstationCode = ref('')
const workstationList = ref([])
// 修正：搜索工作站的表单数据对象
const searchWorkstationForm = ref({code: '', name: ''})

/* ========== 当前工序（新增/修改/删除用） ========== */
let currentProcess = null        // 普通变量即可，无需 window

/* ========== 工具函数 ========== */
const handleSearch = () => {
  const params = {...searchForm.value, pageNum: pagination.value.currentPage, pageSize: pagination.value.pageSize}
  getProductionOrderList(params).then(res => {
    productionOrderList.value = res.data?.list || []
    pagination.value.total = res.data?.total || 0
  }).catch(err => ElMessage.error('加载数据失败：' + (err.message || '未知错误')))
}

const resetSearch = () => {
  Object.assign(searchForm.value, {
    productionOrderCode: '',
    productionOrderName: '',
    productionOrderSource: '',
    materialCode: '',
    materialName: '',
    customerCode: '',
    customerName: '',
    requestDate: ''
  })
  handleSearch()
}

const handleSizeChange = (size) => {
  pagination.value.pageSize = size;
  handleSearch()
}
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page;
  handleSearch()
}

/* ========== 查看工单弹窗 ========== */
const handleGetById = async (row) => {
  dialogTitle.value = '查看工单信息'
  proscheduleDialogVisabel.value = true
  try {
    const res = await getProductionOrderById(row.id)
    if (res.code === 200 && res.data) {
      proscheduleForm.value = {
        ...res.data,
        materialSpecification: res.data.material?.specification || '',
        unitName: res.data.material?.unit?.name || ''
      }
      const wfRes = await getWorkflowByMaterialCode(res.data.materialCode)
      workflowList.value = wfRes.data || []
      if (workflowList.value.length) currentWorkflowId.value = workflowList.value[0].id
    } else {
      ElMessage.error('获取工单详情失败')
      proscheduleDialogVisabel.value = false
    }
  } catch (e) {
    ElMessage.error('加载工单失败：' + e.message)
    proscheduleDialogVisabel.value = false
  }
}

const dialogClose = () => {
  proscheduleForm.value = {}
}

/* ========== 工艺/工序切换 ========== */
const handleWorkflowTabClick = (panel) => {
  currentWorkflowId.value = panel.props.name
}

const handleProcessTabClick = async (panel) => {
  const processId = panel.props.name
  currentProcess = workflowList.value
      .flatMap(w => w.processes || [])
      .find(p => p.id === processId)
  if (!currentProcess) return

  // 清空旧任务
  currentProcess.taskList = []
  try {
    const res = await getProductionTaskByWorkflowId(currentWorkflowId.value)
    if (res.code === 200 && res.data) {
      currentProcess.taskList = res.data.filter(t => t.processId === processId)
    }
  } catch (e) {
    ElMessage.error('加载任务失败：' + e.message)
  }
}

/* ========== 新增 / 修改 / 删除任务 ========== */
const handleAddTask = (process) => {
  currentProcess = process
  productListDialogVisable.value = true
  selectedWorkstationCode.value = ''
  loadWorkstationList()
}

const handleEditTask = (process) => {
  if (!process.taskList || process.taskList.length === 0) {
    ElMessage.warning('没有可修改的任务')
    return
  }
  handleAddTask(process)
}

const handleDeleteTask = (process) => {
  if (!process.taskList || process.taskList.length === 0) {
    ElMessage.warning('没有可删除的任务')
    return
  }
  process.taskList.splice(0, 1)
  ElMessage.success('删除成功')
}

/* ========== 工作站选择弹窗 ========== */
const loadWorkstationList = async () => {
  const params = {
    pageNum: 1,
    pageSize: 50,               // 弹窗里先拉 50 条足够
    code: searchWorkstationForm.value.code.trim(), // 修正：从searchWorkstationForm读取
    name: searchWorkstationForm.value.name.trim()  // 修正：从searchWorkstationForm读取
  }
  const res = await getWorkstationPage(params)
  if (res.code === 200) {
    workstationList.value = res.data.list || []
  } else {
    ElMessage.error('加载工作站失败')
    workstationList.value = []
  }
}

const resetSearchWorkstation = () => {
  searchWorkstationForm.value.code = '' // 修正：清空searchWorkstationForm的code
  searchWorkstationForm.value.name = '' // 修正：清空searchWorkstationForm的name
  loadWorkstationList()
}

const doSelectWorkstation = () => {
  if (!selectedWorkstationCode.value) {
    ElMessage.warning('请选择工作站')
    return
  }
  const ws = workstationList.value.find(w => w.code === selectedWorkstationCode.value)
  if (!ws || !currentProcess) return

  currentProcess.taskList.push({
    taskName: `${currentProcess.processName}-任务${currentProcess.taskList.length + 1}`,
    workstationName: ws.name,
    workstationCode: ws.code,
    scheduledQuantity: 100,
    producedQuantity: 0,
    startProductionTime: null,
    estimatedCompletionTime: null,
    operation: '待生产',
    productionDuration: 0
  })

  ElMessage.success('新增任务成功')
  productListDialogVisable.value = false
}

/* ========== 初始化 ========== */
onMounted(() => handleSearch())
</script>


<style scoped>
.customer-container {
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px; /* 修复：图标垂直居中 */
}
</style>
